/****************************************************************************************
 南京小视科技有限公司
 ****************************************************************************************/
package com.minivision.migrate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.minivision.migrate.dto.PlanetDeviceDTO;
import com.minivision.migrate.dto.PlanetPersonDTO;
import com.minivision.migrate.entity.DeviceApe;
import com.minivision.migrate.entity.HouseInfo;
import com.minivision.migrate.entity.PersonInfo;
import com.minivision.migrate.entity.VillageInfo;
import com.minivision.migrate.mapper.datacenter.DeviceApeMapper;
import com.minivision.migrate.mapper.datacenter.HouseInfoMapper;
import com.minivision.migrate.mapper.datacenter.PersonInfoMapper;
import com.minivision.migrate.mapper.datacenter.VillageInfoMapper;
import com.minivision.migrate.mapper.person.PlanetPersonMapper;
import com.minivision.migrate.mapper.planet.OrgMapper;
import com.minivision.migrate.mapper.salmon.PlanetDeviceMapper;
import com.minivision.migrate.service.MigrateService;
import com.minivision.migrate.service.PlanetService;
import com.minivision.migrate.util.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <Description><br>
 *
 * @author luyaoqiang<br>
 * @version 1.2<br>
 * @taskId <br>
 * @CreateDate 2020/9/29 <br>
 */
@Slf4j
@Service
public class PlanetServiceImpl implements PlanetService {


    @Autowired
    private PlanetPersonMapper planetPersonMapper;

    @Autowired
    private PlanetDeviceMapper planetDeviceMapper;

    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private MigrateService migrateService;

    @Autowired
    private PersonInfoMapper personInfoMapper;
    @Autowired
    private VillageInfoMapper villageInfoMapper;
    @Autowired
    private HouseInfoMapper houseInfoMapper;

    @Autowired
    private DeviceApeMapper deviceApeMapper;

    @Override
    public void dealPlanetPersonByCommunityId(String communityId) {
        log.info("处理人员信息开始 :" + communityId);

        // 根据小区id查询所有的组织id
        List<Integer> orgIdList = migrateService.getAllSubOrgIds(Integer.valueOf(communityId));

        if (CollectionUtil.isEmpty(orgIdList)) {
            log.info("该小区下没有组织信息");
            return;
        }

        // 根据小区id查询小区标识
        VillageInfo villageInfo = new VillageInfo();
        villageInfo.setPlanetOrgId(Integer.valueOf(communityId));
        List<VillageInfo> villageInfos = villageInfoMapper.select(villageInfo);
        if (CollectionUtil.isEmpty(villageInfos)) {
            return;
        }

        VillageInfo dbVillageInfo = villageInfos.get(0);

        int pageNumber = 1;
        int pageSize = 500;

        while (true) {
            Page<PlanetPersonDTO> page = PageHelper.startPage(pageNumber, pageSize);

            // 根据组织id查询人员
            List<PlanetPersonDTO> planetPersonDTOList = planetPersonMapper.queryPlanetPersonByOrgIds(orgIdList);

            for (PlanetPersonDTO planetPersonDTO : planetPersonDTOList) {

                // 根据组织id查询是否已同步过,这才会保存组织下的人员信息
                HouseInfo queryHouseInfo = new HouseInfo();
                queryHouseInfo.setPlanetOrgId(planetPersonDTO.getOrgId());
                List<HouseInfo> houseInfoList = houseInfoMapper.select(queryHouseInfo);

                if (CollectionUtil.isNotEmpty(houseInfoList)) {
                    HouseInfo houseInfo = houseInfoList.get(0);

                    PersonInfo personInfo = new PersonInfo();
                    personInfo.setPlanetPersonId(planetPersonDTO.getId());
                    personInfo.setXm(planetPersonDTO.getName());
                    //        personInfo.setKmsbbz("开门识别标识");
                    personInfo.setKmfsdm("09");
                    personInfo.setXqxxbz(dbVillageInfo.getXqxxbz());// 小区信息标识
                    personInfo.setFwxxbz(houseInfo.getFwxxbz()); // 房屋信息标识
                    personInfo.setCyzjdm("111");// 常用证件代码
                    personInfo.setZjhm(md5Encrypt(planetPersonDTO.getCardNo())); // 证件号码

                    if (null == planetPersonDTO.getUpdateTime()) {
                        personInfo.setGxsj(planetPersonDTO.getCreateTime()); // 数据更新时间
                    } else {
                        personInfo.setGxsj(planetPersonDTO.getUpdateTime()); // 数据更新时间
                    }

                    if (StringUtils.isBlank(planetPersonDTO.getPhone())) {
                        personInfo.setLxdh(md5Encrypt("18166886688"));
                    } else {
                        personInfo.setLxdh(md5Encrypt(planetPersonDTO.getPhone()));
                    }

                    // 这里0是女的
                    if (0 == planetPersonDTO.getSex()) {
                        // 1是女的
                        personInfo.setXbdm(1); // 性别代码
                    } else {
                        // 0是男的
                        personInfo.setXbdm(0); // 性别代码
                    }

                    personInfo.setXp(planetPersonDTO.getShowPhoto()); // 登记相片

                    // 查询该人员是否同步过
                    PersonInfo queryPersonInfo = new PersonInfo();
                    queryPersonInfo.setPlanetPersonId(planetPersonDTO.getId());
                    List<PersonInfo> personInfos = personInfoMapper.select(queryPersonInfo);
                    if (CollectionUtil.isEmpty(personInfos)) {
                        // 新增
                        personInfoMapper.insertSelective(personInfo);
                    } else {
                        // 修改
                        personInfo.setRyxxbz(personInfos.get(0).getRyxxbz());
                        personInfoMapper.updateByPrimaryKeySelective(personInfo);
                    }

                }
            }

            if (pageNumber * pageSize >= page.getTotal()) {
                break;
            }
            pageNumber = pageNumber + 1;
        }

        log.info("处理人员信息结束 end");
    }

    private String md5Encrypt(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        return DigestUtils.md5DigestAsHex(content.getBytes());
    }


    /**
     * 处理设备
     *
     * @param communityId
     */
    @Override
    public void dealDevice(String communityId) {
        log.info("处理设备开始 :" + communityId);

        // 根据小区id查询客户id
        String custId = orgMapper.getCustIdByCommunityId(Integer.valueOf(communityId));

        if (StringUtils.isBlank(custId)) {
            return;
        }

        // 根据小区id查询小区标识
        VillageInfo villageInfo = new VillageInfo();
        villageInfo.setPlanetOrgId(Integer.valueOf(communityId));
        List<VillageInfo> villageInfos = villageInfoMapper.select(villageInfo);
        if (CollectionUtil.isEmpty(villageInfos)) {
            return ;
        }

        VillageInfo dbVillageInfo = villageInfos.get(0);

        // 根据客户id查询设备信息
        List<PlanetDeviceDTO> planetDeviceDTOList = planetDeviceMapper.queryPlanetDeviceByCustId(custId);

        for (PlanetDeviceDTO planetDeviceDTO : planetDeviceDTOList) {

            DeviceApe deviceApe = new DeviceApe();
            deviceApe.setPlanetDeviceSn(planetDeviceDTO.getDeviceCode());
            deviceApe.setSbmc(planetDeviceDTO.getDeviceName());
            deviceApe.setSblx("003"); // 设备类型
            deviceApe.setXqxxbz(dbVillageInfo.getXqxxbz()); // 小区信息标识
            deviceApe.setXqmh(planetDeviceDTO.getRegionName());
//            deviceApe.setLdh("楼栋信息");
//            deviceApe.setDyh("单元信息");
            deviceApe.setIpdz(planetDeviceDTO.getDeviceIpv4());// IP
            deviceApe.setMacdz(planetDeviceDTO.getDeviceMac());// MAC地址
            deviceApe.setZbtx("百度地图采集"); // 坐标体系,默认为百度地图采集

            if (null != planetDeviceDTO.getLongitude()) {
                deviceApe.setDqjd(String.valueOf(planetDeviceDTO.getLongitude()));// 地球经度
            } else {
                deviceApe.setDqjd("118.752792");// 地球经度
            }

            if (null != planetDeviceDTO.getLatitude()) {
                deviceApe.setDqwd(String.valueOf(planetDeviceDTO.getLatitude()));// 地球纬度
            } else {
                deviceApe.setDqwd("31.987165");// 地球纬度
            }

            deviceApe.setCjsj(planetDeviceDTO.getCreateTime()); //  设备信息采集时间，统一格式为yyyy-mm-dd hh24：mi：ss

            // 设备域中，1离线，0在线
            PlanetDeviceDTO deviceStatusDTO = planetDeviceMapper.getDeviceStatusBySn(planetDeviceDTO.getDeviceCode());
            if (null != deviceStatusDTO) {
                if (0 == deviceStatusDTO.getDeviceStatus()) {
                    deviceApe.setSfzxPdbz("1");// 设备是否在线，0-不在线，1-在线
                } else {
                    deviceApe.setSfzxPdbz("0");// 设备是否在线，0-不在线，1-在线
                }

                deviceApe.setZhzxsj(deviceStatusDTO.getDeviceStatusUpdateTime());// 最后在线时间
            }else {
                deviceApe.setSfzxPdbz("0");// 设备是否在线，0-不在线，1-在线
            }

            // 选取如下取值代码：0-其他,1-小区出入口门禁,2-单元出入口门禁
            deviceApe.setWzlx("1");

            // 查询设备的进出类型
            String inOutType = planetDeviceMapper.getInOutTypeBySn(planetDeviceDTO.getDeviceCode());

            // 星环云中，0入口，1出口
            if ("1".equals(inOutType)) {
                // 选取如下取值代码：1-进 ,2-出,3-进出,9-其他
                deviceApe.setXjfx("2");
            } else {
                // 选取如下取值代码：1-进 ,2-出,3-进出,9-其他
                deviceApe.setXjfx("1");
            }

            DeviceApe queryDeviceApe = new DeviceApe();
            queryDeviceApe.setPlanetDeviceSn(planetDeviceDTO.getDeviceCode());
            List<DeviceApe> deviceApes = deviceApeMapper.select(queryDeviceApe);
            if (CollectionUtil.isEmpty(deviceApes)) {
                deviceApeMapper.insertSelective(deviceApe);
            } else {
                deviceApe.setCjsbxxbz(deviceApes.get(0).getCjsbxxbz());
                deviceApeMapper.updateByPrimaryKeySelective(deviceApe);
            }

        }

        log.info("处理设备结束");

    }




}
